package com.stars.easyms.security.jwt;

import com.stars.easyms.security.properties.EasyMsSecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * EasyMsJwt配置类
 *
 * @author guoguifang
 * @date 2020-08-12 17:24
 * @since 1.6.0
 */
@Slf4j
public final class EasyMsJWTConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    private final EasyMsSecurityProperties easyMsSecurityProperties;

    private final EasyMsJWTProvider easyMsJWTProvider;

    public EasyMsJWTConfigurer(EasyMsSecurityProperties easyMsSecurityProperties, EasyMsJWTProvider easyMsJWTProvider) {
        this.easyMsSecurityProperties = easyMsSecurityProperties;
        this.easyMsJWTProvider = easyMsJWTProvider;
    }

    @Override
    public void configure(HttpSecurity httpSecurity) {
        if (!easyMsSecurityProperties.getJwt().isEnabled()) {
            log.info("JWT is not enabled !");
            return;
        }

        // 如果开启jwt则先对jwtProvider初始化
        easyMsJWTProvider.init();
        log.info("JWT enabled successfully !");
        httpSecurity.addFilterBefore(new EasyMsJWTFilter(easyMsSecurityProperties, easyMsJWTProvider), UsernamePasswordAuthenticationFilter.class);
    }
}
